package kk.learn.scala.work._2

/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-02-21
 */

// 定义gamer类， user类和computer类继承于gamer类
// gamer类中定义统一的行为

// 通过伴生对象来进行相应的示例化
// 使用知识点：继承， 伴生对象， apply方法， 抽象类， 主构造器， 主构造中不带val和var时生成的是私有val变量
abstract class Gamer(val name: String) {

  var score = 0
  var win = 0
  var even = 0
  var loss = 0

  // 使用知识点：抽象方法
  def showFist(): Int

  // 使用知识点：${}进行表达式计算
  override def toString = s"$name\t${win * 2 + even}\t$win\t$even\t$loss"
}


class User(name: String) extends Gamer(name) {
  override def showFist(): Int = {
    //提示 读取用户输入， 然后返回
    println("请出拳！1.剪刀  2.石头  3.布")
    // 使用知识点：模式匹配
    //noinspection ScalaDeprecation
    readInt() match {
      case 1 => 1
      case 2 => 2
      case 3 => 3
      case _ =>
        println("输出非法， 默认出布")
        3
    }
  }
}

class Computer(name: String) extends Gamer(name) {
  override def showFist(): Int = {
    // 随机生成一个1到3的数字返回
    Math.ceil(Math.random() * 3).asInstanceOf[Int]
  }
}

object Gamer {
  def apply(gamerType: String, userName: String): Gamer = {
    gamerType match {
      case "user" => new User(userName)
      case _ => new Computer(userName)
    }
  }
}

//noinspection ScalaDeprecation
class Game(p1: Gamer, p2: Gamer) {
  var times = 0

  def play(): Unit = {
    var isDone = false
    while (!isDone) {
      val p1Fist = p1.showFist()
      println("你出拳:", p1Fist match {
        case 1 => "剪刀"
        case 2 => "石头"
        case 3 => "布"
      })
      println(s"${p2.name}出拳!")
      val p2Fist = p2.showFist()
      println(s"${p2.name}出拳:", p2Fist match {
        case 1 => "剪刀"
        case 2 => "石头"
        case 3 => "布"
      })
      val result = p1Fist match {
        case 1 =>
          p2Fist match {
            case 1 => "even"
            case 2 => "loss"
            case 3 => "win"
          }
        case 2 =>
          p2Fist match {
            case 1 => "win"
            case 2 => "even"
            case 3 => "loss"
          }
        case 3 =>
          p2Fist match {
            case 1 => "loss"
            case 2 => "win"
            case 3 => "even"
          }
      }

      result match {
        case "loss" =>
          println("结果: 你输了！ 下次继续努力！")
          p1.loss = p1.loss + 1
          p2.win = p2.win + 1
        case "win" =>
          println("结果: 你赢了了！")
          p1.win = p1.win + 1
          p2.loss = p2.loss + 1
        case "even" =>
          println("结果: 平局！ 下次继续努力！")
          p1.even = p1.even + 1
          p2.even = p2.even + 1
      }
      this.times += 1
      val flag = readLine("是否开始下一轮（y/n）")
      if (flag == "n") {
        println("------------------------------------------------")

        println(s"${p1.name} VS ${p2.name}")
        println(s"对战次数 $times 次")
        println()
        println()
        println("姓名\t得分\t胜局\t平局\t负局")
        println(p1)
        println(p2)
        println("------------------------------------------------")
        isDone = true
      }

    }
  }
}




